<template>
  <div class="statistics">
    <h2>学习统计</h2>

    <div class="stat-cards">
      <div class="stat-card">
        <div class="card-title">今日学习</div>
        <div class="card-value">{{ formatTime(todayStudyTime) }}</div>
        <div class="card-compare">共计学习 {{ todayCompare }}次</div>
      </div>
      <div class="stat-card">
        <div class="card-title">本周学习</div>
        <div class="card-value">{{ formatTime(weekStudyTime) }}</div>
        <div class="card-compare">共计学习 {{ weekCompare }}次</div>
      </div>
      <div class="stat-card">
        <div class="card-title">专注次数</div>
        <div class="card-value">{{ focusCount }}次</div>
        <div class="card-subtitle">平均时长 {{ formatTime(avgFocusTime) }}</div>
      </div>
      <div class="stat-card">
        <div class="card-title">累计天数</div>
        <div class="card-value">{{ totalDays }}天</div>
        <div class="card-subtitle">连续学习{{ streakDays }}天</div>
      </div>
    </div>

    <div class="chart-section">
      <div class="chart-header">
        <h3>本周学习时长趋势</h3>
        <div class="chart-filters">
          <!-- <button
            v-for="period in periods"
            :key="period.value"
            :class="{ active: currentPeriod === period.value }"
            @click="currentPeriod = period.value"
          >
            {{ period.label }}
          </button> -->
        </div>
      </div>
      <div class="chart" ref="timeChart"></div>
    </div>

    <div class="analysis-section">
      <div class="time-distribution">
        <h3>时段分布</h3>
        <div class="chart" ref="distributionChart"></div>
      </div>

      <div class="subject-analysis">
        <h3>学习内容分析</h3>
        <div class="chart" ref="subjectChart"></div>
      </div>
    </div>

    <div class="achievement-section">
      <h3>成就系统</h3>
      <div
        class="achievements"
        v-for="(achievement, index) in achievements"
        :key="index"
      >
        <div
          class="achievement-card"
          :class="{ unlocked: achievement.unlocked }"
        >
          <div class="achievement-icon">{{ achievement.icon }}</div>
          <div class="achievement-info">
            <div class="achievement-name">{{ achievement.name }}</div>
            <div class="achievement-desc">{{ achievement.description }}</div>
            <div class="achievement-progress">
              <div
                class="progress-bar"
                :style="{ width: `${achievement.progress}%` }"
              ></div>
              <span>{{ achievement.progress }}%</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from "vue";
import * as echarts from "echarts";
import { studyApi } from "@/api/study";
export default {
  name: "Statistics",
  setup() {
    const timeChart = ref(null);
    const distributionChart = ref(null);
    const subjectChart = ref(null);
    const currentPeriod = ref("week");
    const allData = ref(null);

    // 模拟数据
    const todayStudyTime = ref(18000000); // 5小时
    const weekStudyTime = ref(108000000); // 30小时
    const todayCompare = ref(15);
    const weekCompare = ref(-5);
    const focusCount = ref(28);
    const avgFocusTime = ref(3600000); // 1小时
    const totalDays = ref(65);
    const streakDays = ref(7);

    const periods = [
      { label: "周", value: "week" },
      { label: "月", value: "month" },
      { label: "年", value: "year" },
    ];

    const achievements = ref([
      {
        id: 1,
        name: "学习新手",
        description: "累计学习次数达到100次",
        icon: "🎯",
        progress: 100,
        unlocked: false,
      },
      {
        id: 2,
        name: "专注达人",
        description: "累计学习时间超过200小时",
        icon: "⏱️",
        progress: 75,
        unlocked: false,
      },
      {
        id: 3,
        name: "持之以恒",
        description: "连续学习20天",
        icon: "📅",
        progress: 23,
        unlocked: false,
      },
    ]);

    onMounted(() => {
      getData();
    });
    const getData = async () => {
      const res = await studyApi.getStatistics();
      allData.value = res;
      console.log(allData.value);
      todayStudyTime.value = res.today.total_duration;
      todayCompare.value = res.today.session_count;
      weekStudyTime.value = res.week.total_duration;
      weekCompare.value = res.week.session_count;
      focusCount.value = res.all.session_count;
      avgFocusTime.value = res.all.total_duration / res.all.session_count;
      totalDays.value = res.all.total_days;
      streakDays.value = res.all.max_continue_days;
      initDistributionChart();
      initTimeChart();
      initSubjectChart();
      achievements.value[0].progress = res.all.session_count;
      if (achievements.value[0].progress >= 100) {
        achievements.value[0].progress = 100;
        achievements.value[0].unlocked = true;
      }
      achievements.value[1].progress = res.all.total_duration / 60 / 2;
      if (achievements.value[1].progress > 100) {
        achievements.value[1].progress = 100;
        achievements.value[1].unlocked = true;
      }
      achievements.value[2].progress = res.all.max_continue_days / 0.2;
      if (achievements.value[2].progress > 100) {
        achievements.value[2].progress = 100;
        achievements.value[2].unlocked = true;
      }
    };

    const initTimeChart = () => {
      const chart = echarts.init(timeChart.value);
      chart.setOption({
        tooltip: {
          trigger: "axis",
        },
        xAxis: {
          type: "category",
          data: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
        },
        yAxis: {
          type: "value",
          name: "学习时长(小时)",
        },
        series: [
          {
            data: allData.value.week.every_duration,
            type: "line",
            smooth: true,
            areaStyle: {},
          },
        ],
      });
    };

    const initDistributionChart = () => {
      const chart = echarts.init(distributionChart.value);
      chart.setOption({
        tooltip: {
          trigger: "item",
        },
        series: [
          {
            type: "pie",
            radius: ["40%", "70%"],
            data: [
              {
                value: allData.value.time_period_analysis.morning,
                name: "上午",
              },
              {
                value: allData.value.time_period_analysis.evening,
                name: "晚上",
              },
              {
                value: allData.value.time_period_analysis.afternoon,
                name: "上午",
              },
            ],
          },
        ],
      });
    };

    const initSubjectChart = () => {
      const data = allData.value.category_analysis;
      const chart = echarts.init(subjectChart.value);
      chart.setOption({
        tooltip: {
          trigger: "item",
        },
        series: [
          {
            type: "pie",
            radius: "50%",
            data: [
              { value: data.primary, name: "小学" },
              { value: data.junior, name: "初中" },
              { value: data.senior, name: "高中" },
              { value: data.university, name: "大学" },
              { value: data.working, name: "在职" },
            ],
          },
        ],
      });
    };

    const formatTime = (ms) => {
      const hours = Math.floor(ms / 3600);
      const minutes = Math.floor((ms % 3600) / 60);
      return `${hours}小时${minutes}分钟`;
    };

    return {
      currentPeriod,
      periods,
      todayStudyTime,
      weekStudyTime,
      todayCompare,
      weekCompare,
      focusCount,
      avgFocusTime,
      totalDays,
      streakDays,
      achievements,
      timeChart,
      distributionChart,
      subjectChart,
      formatTime,
      getData,
    };
  },
};
</script>

<style scoped>
.statistics {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.stat-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 20px;
  margin: 20px 0;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.card-title {
  color: #666;
  font-size: 0.9em;
}

.card-value {
  font-size: 1.8em;
  font-weight: bold;
  margin: 10px 0;
}

.card-compare {
  font-size: 0.9em;
  color: #4caf50;
}

.card-subtitle {
  font-size: 0.9em;
  color: #666;
}

.chart-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin: 20px 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart-filters button {
  margin-left: 10px;
  padding: 5px 15px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 15px;
  cursor: pointer;
}

.chart-filters button.active {
  background: #1976d2;
  color: white;
  border-color: #1976d2;
}

.chart {
  height: 300px;
  width: 100%;
}

.analysis-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
  margin: 20px 0;
}

.time-distribution,
.subject-analysis {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.achievements {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.achievement-card {
  display: flex;
  padding: 15px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  opacity: 0.7;
}

.achievement-card.unlocked {
  opacity: 1;
}

.achievement-icon {
  font-size: 2em;
  margin-right: 15px;
}

.achievement-info {
  flex: 1;
}

.achievement-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.achievement-desc {
  font-size: 0.9em;
  color: #666;
  margin-bottom: 10px;
}

.achievement-progress {
  position: relative;
  height: 4px;
  background: #eee;
  border-radius: 2px;
}

.progress-bar {
  position: absolute;
  height: 100%;
  background: #4caf50;
  border-radius: 2px;
  transition: width 0.3s ease;
}

.achievement-progress span {
  position: absolute;
  right: 0;
  top: -20px;
  font-size: 0.8em;
  color: #666;
}
</style>
